import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import "package:get/get.dart";

import '../h5_upimg.dart' if (dart.library.io) '../andino_upimg.dart';
// import '../andino_upimg.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../common.dart';
import '../kong.dart' if (dart.library.io) '../im/im_manager.dart';

RxInt _index = 0.obs;
RxBool nick = false.obs;

RxList<Map<String, dynamic>> itemsList = <Map<String, dynamic>>[].obs;

RxList<Map<String, dynamic>> itemsList1 =
    <Map<String, dynamic>>[
      {'text': "昵称", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "实名认证", 'item': "", 'ispoint': false, 'iscolor': false},
      // {'text': "国家或地区", 'item': "", 'ispoint': false, 'iscolor': false},
      // {'text': "账户注销", 'item': "中国", 'ispoint': false, 'iscolor': false},
      {'text': "OSG Chat设置", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "UID", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "区块链地址", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "退出当前账户", 'item': "", 'ispoint': false, 'iscolor': false},
    ].obs;

RxList<Map<String, dynamic>> itemsList2 =
    <Map<String, dynamic>>[
      {'text': "登录密码", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "支付密码", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "手机号码", 'item': "", 'ispoint': false, 'iscolor': false},
    ].obs;

RxList<Map<String, dynamic>> itemsList3 =
    <Map<String, dynamic>>[
      // {'text': "关于我们", 'item': "", 'ispoint': false, 'iscolor': false},
      // {'text': "官方公众号", 'item': "", 'ispoint': false, 'iscolor': false},
      // {'text': "官方社群", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "用户协议", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "隐私协议", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "账户注销", 'item': "", 'ispoint': false, 'iscolor': false},
      {'text': "当前版本", 'item': "", 'ispoint': false, 'iscolor': false},
    ].obs;

Future<void> copyToClipboard(BuildContext context, textToCopy) async {
  await Clipboard.setData(ClipboardData(text: textToCopy));
  showTost('已复制到剪贴板');
}

Future<void> _initPackageInfo() async {
  final info = await PackageInfo.fromPlatform();
  version.value = info.version;
  print(version);
}

String? qian = '';
String? hou = '';

final metaid = myget('user')['metaAddress'];

RxString version = ''.obs;

final TextEditingController controller = TextEditingController();

class Setting extends StatefulWidget {
  Setting({super.key});

  @override
  State<Setting> createState() => _SettingPageState();
}

final FocusNode _focusNode = FocusNode();

class _SettingPageState extends State<Setting> {
  RxMap uusuere = {}.obs;
  var user = {};

  @override
  void initState() {
    super.initState();

    if (metaid.isNotEmpty) {
      qian = metaid.substring(0, 5);
      hou = metaid.substring(metaid.length - 4);
    }

    user = myget('user') ?? '';

    uusuere.value = myget('user') ?? '';

    controller.text = user['name'];

    itemsList2[2]['item'] = myget('phone') ?? '';
    itemsList1[0]['item'] = user['name'] ?? '';
    itemsList1[3]['item'] = user['uuid'] ?? '';
    itemsList1[4]['item'] = '$qian...$hou';

    _focusNode.addListener(_handleFocusChange);
  }

  void _handleFocusChange() {
    setState(() {
      // 失去焦点时执行的操作
      if (!_focusNode.hasFocus) {
        postData(url: '/user/name', data: {"name": controller.text}).then((
          res,
        ) {
          if (res != null) {
            showTost('修改成功');
            nick.value = true;
            uusuere.value = {
              'name': controller.text,
              'headimg': uusuere['headimg'],
            };

            var tuser = myget('user') ?? '';
            tuser['name'] = controller.text;
            myset('user', tuser);
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    con(context);
    itemsList.value = itemsList1;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0XFFFFFFFF),
        centerTitle: true,
        leading: buildBackButton(context),
      ),

      body: Column(
        children: [
          SizedBox(height: 10),
          Align(
            child: Stack(
              children: [
                ClipOval(
                  child: Obx(
                    () => GestureDetector(
                      onTap: () async {
                        final result = await ImageUploader.uploadImage();
                        Get.back();
                        if (result != null && result != '') {
                          postData(
                            url: '/user/headimg2',
                            data: {"file": '$result'},
                          ).then((res) {
                            if (res != null) {
                              showTost('修改成功');
                              nick.value = true;

                              uusuere.value = {
                                'name': controller.text,
                                'headimg': result,
                              };

                              var tuser = myget('user') ?? '';
                              tuser['headimg'] = result;
                              myset('user', tuser);
                            }
                          });
                        }
                      },
                      child: Image.network(
                        '${uusuere['headimg']}',
                        width: 80,
                        height: 80,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ),
                // Positioned(
                //   bottom: 0,
                //   right: 0,
                //   child: ClipOval(
                //     child: Image.asset(
                //       'static/aaa.png',
                //       width: 25,
                //       height: 25,
                //       fit: BoxFit.fill,
                //     ),
                //   ),
                // ),
              ],
            ),
          ),
          SizedBox(height: 10),
          Center(
            child: Obx(
              () => Text('${uusuere['name']}', style: TextStyle(fontSize: 12)),
            ),
          ),
          info(),
          movered(),
        ],
      ),
    );
  }
}

RxString shareImage = ''.obs;
RxString oaQrcode = ''.obs;

Widget info() {
  List<Map> items = [
    {'text': "个人资料", "index": 0},
    {'text': "安全设置", "index": 1},
    {'text': "关于OSG", "index": 2},
  ];

  return Container(
    margin: EdgeInsets.only(left: 15, right: 15, top: 50),
    decoration: BoxDecoration(
      border: Border(bottom: BorderSide(color: Color(0xffdddddd), width: 1)),
    ),
    child: Row(
      children: [
        for (var item in items)
          GestureDetector(
            onTap: () {
              _index.value = item['index'];
              if (_index.value == 1) {
                itemsList.value = itemsList2;
              } else if (_index.value == 2) {
                itemsList3.value = [
                  {
                    'text': "用户协议",
                    'item': "",
                    'ispoint': false,
                    'iscolor': false,
                  },
                  {
                    'text': "隐私协议",
                    'item': "",
                    'ispoint': false,
                    'iscolor': false,
                  },
                  {
                    'text': "账户注销",
                    'item': "",
                    'ispoint': false,
                    'iscolor': false,
                  },
                  {
                    'text': "当前版本",
                    'item': "",
                    'ispoint': false,
                    'iscolor': false,
                  },
                ];

                _initPackageInfo().then((onValue) {
                  itemsList3[3]['item'] = version.value;
                });

                getData(url: '/setting/qrcode').then((res) {
                  if (res != null) {
                    if (res['setting']['share_image'] != null) {
                      shareImage.value = res['setting']['share_image'];
                      itemsList3.insert(0, {
                        'text': "官方社群",
                        'item': "",
                        'ispoint': false,
                        'iscolor': false,
                      });
                    }
                    if (res['setting']['oa_qrcode'] != null) {
                      oaQrcode.value = res['setting']['oa_qrcode'];
                      itemsList3.insert(0, {
                        'text': "官方公众号",
                        'item': "",
                        'ispoint': false,
                        'iscolor': false,
                      });
                    }
                    itemsList.value = itemsList3;
                  }
                });
              } else {
                itemsList.value = itemsList1;
              }
            },
            child: Obx(
              () => Container(
                margin: EdgeInsets.only(right: 20),
                padding: EdgeInsets.only(bottom: 5),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color:
                          _index.value == item['index']
                              ? Color(0xff333333)
                              : Color(0xffffffff), // 底部边框颜色
                      width: 2, // 底部边框宽度
                    ),
                  ),
                ),
                child: Text(item['text']),
              ),
            ),
          ),
      ],
    ),
  );
}

Widget movered() {
  offOrder(type) {
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.transparent,
        content: Stack(
          children: [
            Image.asset('static/tan.png', width: 250, fit: BoxFit.fitWidth),
            Positioned(
              top: 40,
              left: 0,
              right: 0,
              child: Align(
                child: Column(
                  children: [
                    Text(
                      type == '1' ? '官方社群' : '官方公众号',
                      style: TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 10),
                    Text(
                      '扫一扫二维码，关注我们',
                      style: TextStyle(fontSize: 12, color: Color(0XFF999999)),
                    ),
                    SizedBox(height: 15),
                    Obx(
                      () => Image.network(
                        type == '1' ? '$shareImage' : '$oaQrcode',
                        width: 170,
                        fit: BoxFit.fitWidth,
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Get.back();
                      },
                      child: Container(
                        height: 40,
                        margin: EdgeInsets.only(top: 20, bottom: 30),
                        alignment: Alignment.center,
                        width: 210,
                        decoration: BoxDecoration(
                          color: Color(0XFF0F172B),
                          borderRadius: BorderRadius.circular(50),
                        ),
                        child: Text(
                          '确认',
                          style: TextStyle(
                            fontSize: 16,
                            color: Color(0XFFFFFFFF),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  return Obx(
    () => Expanded(
      child: ListView.builder(
        itemCount: itemsList.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              if (_index.value == 0) {
                if (itemsList[index]['text'] == '退出当前账户') {
                  myset('token', '');
                  Get.offAllNamed('/login/login_type');

                  ImManager().logout();
                } else if (itemsList[index]['text'] == '实名认证') {
                  toNamed('/user/certification');
                } else if (itemsList[index]['text'] == 'OSG Chat设置') {
                  Get.dialog(
                    AlertDialog(
                      backgroundColor: Colors.transparent,
                      content: Stack(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(15.0),
                            child: Image.asset(
                              'static/qidai.png',
                              width: 250,
                              fit: BoxFit.fitWidth,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }
              } else if (_index.value == 1) {
                if (itemsList[index]['text'] == '登录密码') {
                  toNamed('/user/change_password?type=1');
                } else if (itemsList[index]['text'] == '电子邮箱') {
                  toNamed('/user/change_password?type=2');
                } else if (itemsList[index]['text'] == '支付密码') {
                  toNamed('/user/change_password?type=3');
                }
              } else {
                if (itemsList[index]['text'] == '账户注销') {
                  Get.dialog(
                    AlertDialog(
                      backgroundColor: Color(0xffffffff),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      content: Container(
                        height: 140,
                        child: Column(
                          children: [
                            SizedBox(height: 25),
                            Text('您的账号将被注销，', style: TextStyle(fontSize: 12)),
                            SizedBox(height: 5),
                            Text('确认注销?', style: TextStyle(fontSize: 12)),
                            SizedBox(height: 30),
                            Row(
                              children: [
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      postData(
                                        url: '/user/batalan',
                                        data: {},
                                      ).then((res) {
                                        if (res != null) {
                                          showTost('注销成功');

                                          Timer(Duration(seconds: 1), () {
                                            Get.offAllNamed(
                                              '/login/login_type',
                                            );
                                          });
                                        }
                                      });
                                    },
                                    child: Container(
                                      width: 80,
                                      height: 35,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: Color(0XFFF5F5F5),
                                        borderRadius: BorderRadius.circular(35),
                                      ),
                                      child: Text(
                                        '确认注销',
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: Color(0XFFEF0000),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(width: 15),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      Get.back();
                                    },
                                    child: Container(
                                      width: 80,
                                      height: 35,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: Color(0XFFF5F5F5),
                                        borderRadius: BorderRadius.circular(35),
                                        gradient: LinearGradient(
                                          colors: [
                                            Color(0xff2189E7),
                                            Color(0xffBF67F8),
                                          ],
                                          begin: Alignment.topLeft, // 渐变开始的位置
                                          end: Alignment.bottomRight, // 渐变结束的位置
                                        ),
                                      ),
                                      child: Text(
                                        '取消',
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: Color(0XFFFFFFFF),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                } else if (itemsList[index]['text'] == '用户协议') {
                  toNamed('/agreement?type=1');
                } else if (itemsList[index]['text'] == '隐私协议') {
                  toNamed('/agreement?type=2');
                } else if (itemsList[index]['text'] == '官方社群') {
                  offOrder('1');
                } else if (itemsList[index]['text'] == '官方公众号') {
                  offOrder('2');
                }
              }
            },
            child: Padding(
              padding: EdgeInsets.only(
                left: 15,
                right: 15,
                top: 25,
                bottom: 25,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    itemsList[index]['text'],
                    style: TextStyle(
                      fontSize: 16,
                      color:
                          itemsList[index]['text'] == '退出当前账户'
                              ? Color(0XFFEF0000)
                              : Color(0XFF333333),
                    ),
                  ),
                  Row(
                    children: [
                      itemsList[index]['ispoint']
                          ? Container(
                            width: 4,
                            height: 4,
                            margin: EdgeInsets.only(right: 10),
                            decoration: BoxDecoration(
                              color: Color(0xffef0000),
                              borderRadius: BorderRadius.circular(4),
                            ),
                          )
                          : SizedBox(),

                      itemsList[index]['text'] == '昵称'
                          ? Container(
                            width: 200,
                            child: TextField(
                              maxLines: 1,
                              controller: controller,
                              focusNode: _focusNode,
                              onSubmitted: (_) => _focusNode.unfocus(),
                              textAlign: TextAlign.end,
                              keyboardType: TextInputType.text,
                              textInputAction: TextInputAction.done,
                              style: TextStyle(fontSize: 14),
                              decoration: InputDecoration(
                                isCollapsed: true, //设置高度
                                // contentPadding: EdgeInsets.all(15),
                                contentPadding: EdgeInsets.zero, // 去掉内边距
                                hintStyle: TextStyle(color: Color(0xff999999)),
                                border: InputBorder.none, // 隐藏输入框默认边框
                                hintText: '填写昵称', // 提示文本
                              ),
                            ),
                          )
                          : Text(
                            itemsList[index]['item'],
                            style: TextStyle(
                              fontSize: 14,
                              color:
                                  itemsList[index]['iscolor']
                                      ? Color(0xff999999)
                                      : Color(0xff333333),
                            ),
                          ),

                      if (itemsList[index]['text'] != '区块链地址' &&
                          itemsList[index]['text'] != '退出当前账户' &&
                          itemsList[index]['text'] != 'UID' &&
                          itemsList[index]['text'] != '手机号码' &&
                          itemsList[index]['text'] != '当前版本')
                        Icon(
                          Icons.chevron_right,
                          size: 20.0, // 你可以根据需要调整大小
                          color: Color(0xff2c2c2c), // 你可以根据需要调整颜色
                        ),
                      if (itemsList[index]['text'] == '区块链地址')
                        GestureDetector(
                          onTap: () {
                            copyToClipboard(context, metaid);
                          },
                          child: Icon(Icons.copy, size: 13),
                        ),
                    ],
                  ),
                ],
              ),
            ),
          );
        },
      ),
    ),
  );
}
